package net.esj.basic.core.business.handler;

import java.io.Serializable;
import java.util.Collection;

import javax.inject.Inject;

import net.esj.basic.core.view.tools.searcher.Searcher;
import net.esj.basic.core.view.tools.searcher.SearcherColumn;
import net.esj.basic.dao.querybuilder.OrderExpression;
import net.esj.basic.dao.querybuilder.QueryBuilder;
import net.esj.basic.dao.querybuilder.QueryBuilderFactory;
import net.esj.basic.dao.querybuilder.SymbolExpression;
import net.esj.basic.pojo.MObject;
import net.esj.basic.service.DefaultService;

public abstract class AbstractMObjectSearchHandler<T extends MObject> implements MObjectSearchHandler<T> {

	private DefaultService defaultService;
	
	@Override
	public Collection<T> search(Searcher searcher) {
		QueryBuilder<T> qb = QueryBuilderFactory.create(mObjectClass());
		for(SearcherColumn sc : searcher.getColumns()){
			if(sc.getKey().startsWith(identifyKey()+SEARCH_KEY_SPLIT)){
				String key = sc.getKey().substring(0,identifyKey().length()+SEARCH_KEY_SPLIT.length());
				SymbolExpression.append(qb, key,sc.getType() , sc.getValue());
				searcher.clearById(sc.getId());
			}
		}
		return defaultService.queryListByQueryBuilder(qb);
	}

	@Override
	public void append(QueryBuilder qb,String key, Searcher searcher) {
		if(!check(searcher)){
			return;
		}
		Collection<T> collection = search(searcher);
		Serializable[] ids = new Serializable[collection.size()];
		int i=0;
		for(T t : collection){
			ids[i] = t.getId();
			i++;
		}
		qb.in(key, ids);
	}

	@Inject
	public void setDefaultService(DefaultService defaultService) {
		this.defaultService = defaultService;
	}
	
	private boolean check(Searcher searcher){
		for(SearcherColumn sc : searcher.getColumns()){
			if(sc.getKey().startsWith(identifyKey()+SEARCH_KEY_SPLIT)){
				return true;
			}
		}
		return false;
	}
}
